import { Component, createRef } from 'react';
import { Toast } from 'antd-mobile';
import { http } from '../../utils/http';
import './index.scss';
import { List, AutoSizer } from 'react-virtualized';
import { getCurrentCity } from '../../utils';
import NavBar from '../../components/NavBar';

const ROW_HEIGHT = 45;
const TITLE_HEIGHT = 45;

const formatLetter = val => {
  switch (val) {
    default:
      return val.toUpperCase();
    case 'hot':
      return '热门城市';
    case '#':
      return '当前定位';
  }
};

const avaliableCity = ['北京', '上海', '广州', '深圳'];

export default class CityList extends Component {
  state = {
    cityData: {},
    cityIndex: [],
    activeIndex: 0,
  };
  componentDidMount() {
    this.getCityData(() => this.virtualListRef.current.measureAllRows());
  }
  virtualListRef = createRef();
  render() {
    const { cityIndex, activeIndex } = this.state;
    return (
      <div className='CityList'>
        <NavBar>城市选择</NavBar>
        <AutoSizer className='autoSizer'>
          {({ width, height }) => {
            return (
              <List
                ref={this.virtualListRef}
                className='virtual-list'
                width={width}
                height={height}
                rowCount={cityIndex.length}
                rowHeight={this.calcItemHeight}
                rowRenderer={this.rowRenderer}
                scrollToAlignment='start'
                onRowsRendered={this.onRowsRendered}
              />
            );
          }}
        </AutoSizer>
        <div className='order-content'>
          {cityIndex.map((item, index) => (
            <div
              className={'order-item' + (activeIndex === index ? ' active' : '')}
              onClick={() => this.handleOrderClick(index)}
              key={item}
            >
              {item === 'hot' ? '热' : item.toUpperCase()}
            </div>
          ))}
        </div>
      </div>
    );
  }
  rowRenderer = ({ key, index, style }) => {
    const { cityData, cityIndex } = this.state;
    return (
      <div key={key} style={style}>
        <div className='title'>{formatLetter(cityIndex[index])}</div>
        {cityData[cityIndex[index]].map(item => (
          <div className='item' key={item.value} className='row-item' onClick={() => this.handleCityChange(item)}>
            {item.label}
          </div>
        ))}
      </div>
    );
  };
  onRowsRendered = ({ startIndex }) => {
    const { activeIndex } = this.state;
    if (activeIndex !== startIndex) {
      this.setState({ activeIndex: startIndex });
    }
  };
  handleCityChange = item => {
    if (avaliableCity.indexOf(item.label) > -1) {
      window.localStorage.setItem('zf_city', JSON.stringify(item));
      this.props.history.go(-1);
      Toast.success('切换城市成功', 1, null, false);
    } else {
      Toast.info(`${item.label}没有房源数据`, 1, null, false);
    }
  };
  handleOrderClick = index => {
    this.setState({ activeIndex: index });
    this.virtualListRef.current.scrollToRow(index);
  };
  calcItemHeight = ({ index }) => {
    const { cityData, cityIndex } = this.state;
    return TITLE_HEIGHT + cityData[cityIndex[index]].length * ROW_HEIGHT;
  };
  async getCityData(cb) {
    const { cityData, cityIndex } = this.state;
    Toast.loading('加载中...', 0, null, false);
    const {
      data: { body: citys },
    } = await http.get('/area/city?level=1');
    const {
      data: { body: hotCitys },
    } = await http.get('/area/hot');
    Toast.hide()
    citys.forEach(item => {
      const firstLetter = item.short.substr(0, 1);
      if (cityData[firstLetter]) {
        cityData[firstLetter].push(item);
      } else {
        cityData[firstLetter] = [item];
      }
    });
    Object.keys(cityData).forEach(item => cityIndex.push(item));
    cityIndex.sort();
    // 热门城市
    cityData['hot'] = hotCitys;
    cityIndex.unshift('hot');
    // 当前定位城市
    const curCity = await getCurrentCity();
    cityData['#'] = [curCity];
    cityIndex.unshift('#');
    this.setState({
      cityData,
      cityIndex,
    });
    cb && cb();
  }
}
